#include <iostream>
#include <string>
#include <cassert>
#include <unistd.h>
#include <vector>
#include "Task.hpp"

using namespace std;

const int gnum = 5;
Task t;

class EndPoint
{
public:
    pid_t _child_id;
    int _write_fd;

public:
    EndPoint(int id, int fd) : _child_id(id), _write_fd(fd)
    {
    }
    ~EndPoint()
    {
    }
};

// 子进程要执行的方法
void WaitCommand()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(int));
        if (n == sizeof(int))
        {
            t.Execute(command);
        }
        else if (n == 0)
        {
            break;
        }
        else
        {
            break;
        }
    }
}

void createProcesses(vector<EndPoint> *end_points)
{
    // 1.先进行构建控制结构,父进程写，子进程读
    for (int i = 0; i < gnum; i++)
    {
        // 1.1 创建管道
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;

        // 1.2 创建进程
        pid_t id = fork();
        assert(id != -1);
        // 一定是子进程
        if (id == 0)
        {
            // 1.3 关闭不需要的fd
            close(pipefd[1]);
            dup2(pipefd[0],0);

            WaitCommand();

            close(pipefd[0]);
            exit(0);
        }

        // 一定是父进程
        // 1.3 关闭不需要的fd
        close(pipefd[0]);

        // 1.4 将新的子进程和他的管道写端，构建对象
        end_points->push_back(EndPoint(id, pipefd[1]));
    }
}

int main()
{
    //1.先进行构建控制结构, 父进程写入，子进程读取 ， bug?
    vector<EndPoint> end_points;
    createProcesses(&end_points);

    //父进程会继续向下执行
    int num=0;
    while(true)
    {
        int command = COMMAND_LOG;

        int index = rand()%end_points.size();

        write(end_points[index]._write_fd,&command,sizeof(command));
        sleep(1);
    }
    return 0;
}